package java_thinking.unit_17._17_9_10;

import java.util.ArrayList;
import java.util.List;

/**
 * @Desc:   创建一个封装String数组的容器，该容器只允许添加和读取String，因此在使用过程中不存在任何转型问题
 *          如果在添加下一个元素时，内部数据没有足够的控件，该容器应该自动调整尺寸，在main()中比较该容器与
 *          ArrayList<String>的性能
 * @author: cww
 * @DateTime: 2019-04-21 11:20
 */
class StringContainer {
    private String[] array;
    private int index;
    private static final int INCR = 255;

    public StringContainer() {
        array = new String[10];
    }
    public StringContainer(int size) {
        array = new String[size];
    }

    public void add(String s) {
        if (index >= array.length) {
            String[] tmp = new String[array.length + INCR];
            for (int i = 0; i < array.length; i++) {
                tmp[i] = array[i];
            }
            index = array.length;
            array = tmp;
        }
        array[index++] = s;
    }

    public String get(int i) {
        return array[i];
    }
    public int size() {
        return index;
    }
}
/**
 * @author asd730520@live.com
 */
public class E31_StringContainer {
    static final int LOOPS = 10000;
    static List<Test<List<String>>> alTests = new ArrayList<>();
    static List<Test<StringContainer>> scTest = new ArrayList<>();
    static {
        alTests.add(new Test<List<String>>("addget") {
            @Override
            int test(List<String> container, TestParam tp) {
                for (int i = 0; i < LOOPS; i++) {
                    container.add(Integer.toString(i));
                    container.get(i);
                }
                return LOOPS;
            }
        });
        scTest.add(new Test<StringContainer>("addget") {
            @Override
            int test(StringContainer container, TestParam tp) {
                for (int i = 0; i < LOOPS; i++) {
                    container.add(Integer.toString(i));
                    container.get(i);
                }
                return LOOPS;
            }
        });
    }

    public static void main(String[] args) {
        Tester.defaultParams = TestParam.array(LOOPS,1);
        Tester.run(new ArrayList<>(LOOPS),alTests);
        Tester.run(new StringContainer(LOOPS),scTest);
    }
}
